package com.thuanpq60023.easyenglish.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import bin.com.*;
import com.bubblewaretechnology.*;
import com.bubblewaretechnology.i18n.I18nTranslator;
import com.thuanpq60023.easyenglish.R;
import com.thuanpq60023.easyenglish.bus.UnitBus;
import com.thuanpq60023.easyenglish.bus.VocabularyBus;
import com.thuanpq60023.easyenglish.entity.UnitEntity;
import com.thuanpq60023.easyenglish.entity.VocabEntity;
import com.thuanpq60023.easyenglish.global.GlobalFont;
import com.thuanpq60023.easyenglish.global.GlobalFunction;
import com.thuanpq60023.easyenglish.helper.ReadXLS;
import com.thuanpq60023.easyenglish.view.Header;

public class ImportActivity extends Activity {
	private VocabularyBus mEasyEnglishTBBus;
	private UnitBus mUnitBus;
	private Button btnImport;
	private Button btnRemove;
	private Button btnTransEtoV;
	private Button btnTransVtoE;
	private Button btnXSLImport;
	private EditText edtUnit;
	private EditText edtWord;
	private EditText edtMean;
	private Spinner spnType;
	private Spinner spnUnit;
	private EditText edtExample;
	private Toast mToast;
	private Bundle mBundle;
	private VocabEntity mVocabEntity;
	private Typeface font;
	private ProgressDialog progress_dialog;
	private static final int PROGRESS_DIALOG = 0;
	private boolean[] checkedItems;
	private ReadXLS mReadXLS;
	private AlertDialog.Builder mBuilder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.import_layout);
		mBundle = getIntent().getExtras();

		initChild();
		initView();
		initData();
		initHeader();
	}

	private void initChild() {
		Log.e("ThuanPQ", "initChild()");
		mEasyEnglishTBBus = new VocabularyBus(ImportActivity.this);
		mUnitBus = new UnitBus(ImportActivity.this);
		font = new GlobalFont(getApplicationContext()).getUVNBanTay();
		mReadXLS = new ReadXLS(this);
		progress_dialog = new ProgressDialog(ImportActivity.this);
		progress_dialog.setMessage("Loading please wait..");
		progress_dialog.setCancelable(false);
	}

	public void initHeader() {
		Log.e("ThuanPQ", "initHeader()");
		Header header = new Header(this);
		header.setTextTitle(getString(R.string.import_layout));
		header.getImvMenu().setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void initData() {
		Log.e("ThuanPQ", "initData()");
		try {
			mVocabEntity = mEasyEnglishTBBus.getVocabByWordAndType(
					mBundle.getString("Word"), mBundle.getString("Type"));
			for (int i = 0; i < spnUnit.getCount(); i++) {
				if (spnUnit.getItemAtPosition(i).toString().trim()
						.equalsIgnoreCase(mVocabEntity.getUnit())) {
					spnUnit.setSelection(i);
					break;
				}
			}
			edtWord.setText(mVocabEntity.getWord());
			edtMean.setText(mVocabEntity.getMean());
			edtExample.setText(mVocabEntity.getExample());
			for (int i = 0; i < spnType.getCount(); i++) {
				if (spnType.getItemAtPosition(i).toString().trim()
						.equalsIgnoreCase(mVocabEntity.getType())) {
					spnType.setSelection(i);
					break;
				}
			}
		} catch (NullPointerException e) {
			Log.e("ThuanPQ", e.toString());
		}
	}

	private void initView() {
		Log.e("ThuanPQ", "initView()");
		btnImport = (Button) findViewById(R.id.add_layout_btn_import);
		btnRemove = (Button) findViewById(R.id.add_layout_btn_remove);
		btnTransEtoV = (Button) findViewById(R.id.add_layout_btn_etov);
		btnTransVtoE = (Button) findViewById(R.id.add_layout_btn_vtoe);
		btnXSLImport = (Button) findViewById(R.id.add_layout_btn_xsl_import);
		edtUnit = (EditText) findViewById(R.id.add_layout_edt_unit);
		edtUnit.setTypeface(font);
		spnUnit = (Spinner) findViewById(R.id.add_layout_spn_unit);
		edtWord = (EditText) findViewById(R.id.add_layout_edt_word);
		edtWord.setTypeface(font);
		edtMean = (EditText) findViewById(R.id.add_layout_edt_mean);
		edtMean.setTypeface(font);
		spnType = (Spinner) findViewById(R.id.add_layout_spn_type);
		edtExample = (EditText) findViewById(R.id.add_layout_edt_example);
		edtExample.setTypeface(font);

		// new Thread() {
		// public void run() {
		// mEditextState.setListener(edtUnit);
		// }
		// }.start();
		//
		// new Thread() {
		// public void run() {
		// mEditextState.setListener(edtWord);
		// }
		// }.start();
		//
		// new Thread() {
		// public void run() {
		// mEditextState.setListener(edtMean);
		// }
		// }.start();
		//
		// new Thread() {
		// public void run() {
		// mEditextState.setListener(edtExample);
		// }
		// }.start();

		btnImport.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				insertVocab();
			}
		});

		btnRemove.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				removeVocab();
			}
		});

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, mUnitBus.getAllUnitName());
		adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
		spnUnit.setAdapter(adapter);

		spnUnit.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Log.e("ThuanPQ", "Selected: " + String.valueOf(arg2));
				Log.e("ThuanPQ", "Selected: "
						+ arg0.getItemAtPosition(arg2).toString());
				edtUnit.setText(arg0.getItemAtPosition(arg2).toString());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		btnXSLImport.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				progress_dialog.show();
				MultiImportPrepare mMultiImport = new MultiImportPrepare();
				mMultiImport.execute(null);
			}
		});

		btnTransEtoV.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
			}
		});

		btnTransVtoE.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// try {
				// Translate.setHttpReferrer("http://google.com");
				// String rs_trans = Translate.execute(edtMean.getText()
				// .toString().trim(), Language.VIETNAMESE,
				// Language.ENGLISH);
				// AlertDialog alertDialog = new AlertDialog.Builder(
				// ImportActivity.this).create();
				// alertDialog.setTitle("Translated:");
				// alertDialog.setMessage(rs_trans);
				// alertDialog.setCanceledOnTouchOutside(true);
				// Log.e("ThuanPQ", rs_trans);
				// alertDialog.show();
				// } catch (Exception e) {
				// Log.e("ThuanPQ", e.toString());
				// }
			}
		});
	}

	private void removeVocab() {
		Log.e("ThuanPQ", "removeVocab()");
		boolean valid = false;
		String word = edtWord.getText().toString().trim();
		String type = spnType.getSelectedItem().toString().trim();

		if (mEasyEnglishTBBus.getVocabByWordAndType(word, type) != null) {
			valid = mEasyEnglishTBBus.deleteVocabByWordAndType(word, type);
			if (valid) {
				edtWord.setText("");
				edtMean.setText("");
				spnType.setSelection(0);
				edtExample.setText("");
				createToast("Removed: " + word);
			} else {
				createToast("Not found: " + word);
			}
		}
	}

	private void insertVocab() {
		Log.e("ThuanPQ", "insertVocab()");
		boolean valid = false;
		VocabEntity entity;
		String unit = edtUnit.getText().toString().trim();
		String word = edtWord.getText().toString().trim();
		String mean = edtMean.getText().toString().trim();
		String type = spnType.getSelectedItem().toString().trim();
		String example = edtExample.getText().toString().trim();
		String createdate = GlobalFunction.getCurrentDate();

		if (!word.equalsIgnoreCase("") && !mean.equalsIgnoreCase("")) {
			entity = new VocabEntity(word, mean, type, example, unit,
					createdate, 1, 1);
			if (mEasyEnglishTBBus.getVocabByWordAndType(word, type) != null) {
				valid = mEasyEnglishTBBus.updateVocabByWord(entity);
			} else {
				valid = mEasyEnglishTBBus.insertVocab(entity);
			}
			if (valid) {
				edtWord.setText("");
				edtMean.setText("");
				spnType.setSelection(0);
				edtExample.setText("");

				mUnitBus.insertUnit(new UnitEntity(unit, createdate));

				createToast("Imported: " + word);
			} else {
				createToast("Can not import: " + word);
			}
		} else {
			createToast("Word and mean must be filled with text!");
		}
	}

	private void createToast(String text) {
		mToast = Toast.makeText(ImportActivity.this, text, Toast.LENGTH_SHORT);
		mToast.show();
	}

	class MultiSheetsImport extends AsyncTask<String, Void, String> {

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mHandler.sendEmptyMessage(PROGRESS_DIALOG);
		}

		@Override
		protected String doInBackground(String... params) {
			mReadXLS.multiImport(checkedItems);
			return null;
		}
	}

	class MultiImportPrepare extends
			AsyncTask<String, Void, AlertDialog.Builder> {

		@Override
		protected AlertDialog.Builder doInBackground(String... params) {
			Log.e("ThuanPQ", "doInBackground");
			String[] mSheetsName = mReadXLS.getSheetName();
			if (mSheetsName == null || mSheetsName.length <= 0)
				return null;
			checkedItems = new boolean[mSheetsName.length];
			for (boolean aBool : checkedItems)
				aBool = false;
			mBuilder = new AlertDialog.Builder(ImportActivity.this);
			mBuilder.setTitle("Choose");
			mBuilder.setMultiChoiceItems(mSheetsName, checkedItems,
					new OnMultiChoiceClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which,
								boolean isChecked) {
							checkedItems[which] = isChecked;
						}
					});

			mBuilder.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});

			mBuilder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							progress_dialog.show();
							new MultiSheetsImport().execute(null);
						}
					});

			return mBuilder;
		}

		@Override
		protected void onPostExecute(AlertDialog.Builder result) {
			super.onPostExecute(result);
			Log.e("ThuanPQ", "onPostExecute");
			result.show();
			mHandler.sendEmptyMessage(PROGRESS_DIALOG);
		}
	}

	Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case PROGRESS_DIALOG:
				try {
					progress_dialog.dismiss();
				} catch (Exception e) {
				}
				break;

			default:
				break;
			}

			return false;
		}
	});
}